package entity

import (
	"time"
	"yak.admin/src/util"
)

type User struct {
	Id            uint   `gorm:"auto"`
	Username      string `gorm:"type:varchar(64);index"`
	Token         string `gorm:"type:varchar(64);unique"`
	Password      string `gorm:"size=32"`
	Nickname      string `gorm:"size=32"`
	Sex           int
	Age           int
	Province      string `gorm:"size=16"`
	City          string `gorm:"size=16"`
	County        string `gorm:"size=16"`
	Address       string `gorm:"type:varchar(255)"`
	Company       string `gorm:"type:varchar(255)"`
	Job           string `gorm:"size=128"`
	JobRank       string `gorm:"size=128"`
	Phone         string `gorm:"type:varchar(11);unique"`
	Avatar        string `gorm:"type:varchar(255);default(avatar/user/default.png)"`
	LastLoginTime int64
	CreatedAt     int64
	Status        int
}

func (user *User) GetPassword(password string) string {
	authKey := util.GetSystemValue("auth_key")
	var str = password + authKey
	return util.Md5(str)
}

func (user *User) SetPassword(password string) {
	user.Password = user.GetPassword(password)
}

func (user *User) SetToken() {
	salt := util.RandString(10)
	authKey := util.GetSystemValue("auth_key")
	var str = user.Phone + ":" + salt + ":" + authKey
	user.Token = util.Md5(str)
}

func (user *User) CheckPassword(password string) bool {
	return user.Password == user.GetPassword(password)
}

func (user *User) Info() map[string]interface{} {
	f := util.Formatter{}
	return map[string]interface{}{
		"id":            user.Id,
		"username":      user.Username,
		"nickname":      user.Nickname,
		"age":           user.Age,
		"company":       user.Company,           // 工作单位
		"job":           user.Job,               // 职位
		"job_rank":      user.JobRank,           // 职级
		"sex_label":     f.AsSexLabel(user.Sex), // 0 保密 1 男 2 女
		"sex":           user.Sex,
		"phone":         user.Phone,                 // 手机号
		"avatar":        util.GetImage(user.Avatar), // 头像
		"province":      user.Province,
		"city":          user.City,
		"county":        user.County,
		"address":       user.Address,
		"register_time": f.AsDatetime(user.CreatedAt),
		"is_checked":    user.Status == util.UserStatusOK,
	}
}

func (user *User) RefreshLoginTime() {
	user.LastLoginTime = time.Now().Unix()
}

func (user *User) Editor(attrs map[string]interface{}) int64 {
	db := util.GetMysqlPool().Handler()
	return db.Model(user).Updates(attrs).RowsAffected
}

func (user *User) TableName() string {
	return "user"
}

type Message struct {
	Id        uint   `gorm:"auto"`
	Message   string `gorm:"type:varchar(255)"`
	UserId    uint   `gorm:"index"`
	CreatedAt string `gorm:"type:datetime;index"`
	Type      int    // 0 系统消息
}

func (m *Message) TableName() string {
	return "messages"
}
